package com.snowy.hidden.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snowy.framework.common.base.dto.SaBaseLoginUser;
import com.snowy.framework.common.base.vo.LoginUser;
import com.snowy.framework.common.resp.BaseResp;
import com.snowy.framework.common.resp.BaseRespUtil;
import com.snowy.hidden.biz.domain.req.SysUserUpdatePwdParam;
import com.snowy.hidden.biz.domain.req.UserReq;
import com.snowy.hidden.constant.AuthConstant;
import com.snowy.hidden.constant.AuthErrorCode;
import com.snowy.hidden.constant.RedisConstant;
import com.snowy.hidden.user.domain.model.AppletUser;
import com.snowy.hidden.user.domain.model.SysOrg;
import com.snowy.hidden.user.domain.model.SysUser;
import com.snowy.hidden.user.mapper.AppletUserMapper;
import com.snowy.hidden.user.mapper.SysOrgMapper;
import com.snowy.hidden.user.mapper.SysUserMapper;
import com.snowy.hidden.user.service.SysRoleService;
import com.snowy.hidden.user.service.SysUserService;
import com.snowy.hidden.util.CommonCryptogramUtil;
import com.snowy.redis.RedisStaticUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户(SysUser)表服务实现类
 *
 * @author makejava
 * @since 2023-11-29 23:33:41
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {


    @Autowired
    private AppletUserMapper appletUserMapper;
    @Autowired
    private SysOrgMapper sysOrgMapper;
    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public void updatePassword(SysUserUpdatePwdParam sysUserUpdatePwdParam, LoginUser sysUser) {
        //String password = sysUserUpdatePwdParam.getPassword();
        String newPassword = sysUserUpdatePwdParam.getNewPassword();
//        if (!CommonCryptogramUtil.doHashValue(password).equals(sysUser.getPassword())) {
//            throw new UABPException("原密码错误");
//        }
        this.update(new LambdaUpdateWrapper<SysUser>().eq(SysUser::getId,
                sysUser.getPlatformUserId()).set(SysUser::getPassword,
                CommonCryptogramUtil.doHashValue(newPassword)));
    }

    @Override
    public BaseResp updateUser(UserReq userReq, LoginUser userRedisInfo) {
        LoginUser loginUser =  AuthConstant.userLocal.get();
        AppletUser appletUser=appletUserMapper.selectById(userRedisInfo.getUserId());
        if (ObjectUtil.isEmpty(appletUser)){
            return BaseRespUtil.Error(AuthErrorCode.TOKEN_NO_USERINFO_ERR.getReturnCode(),AuthErrorCode.TOKEN_NO_USERINFO_ERR.getReturnMsg());
        }
        appletUser.setNickName(userReq.getNickName());
        appletUser.setPhone(userReq.getPhone());
        appletUser.setAddress(userReq.getAddress());
        appletUser.setProvince(userReq.getProvince());
        appletUser.setCity(userReq.getCity());
        appletUser.setDistrict(userReq.getDistrict());

        // 查询是否内部员工
        SysUser sysUser = this.getBaseMapper().getByPhone(CommonCryptogramUtil.doSm4CbcEncrypt(userReq.getPhone()));
        if(ObjectUtil.isNotEmpty(sysUser)){
            SysOrg sysOrg = sysOrgMapper.selectById(sysUser.getOrgId());
            appletUser.setInnerAccount(1);
            appletUser.setPlatformUserId(sysUser.getId());
            appletUser.setOrgId(sysUser.getOrgId());
            appletUser.setOrgName(sysOrg.getName());
        }

        appletUserMapper.updateById(appletUser);

        //重新获取用户身份
        BeanUtils.copyProperties(appletUser,loginUser);
        loginUser.setUserName(appletUser.getNickName());
        List<String> roleCodeList = this.sysRoleService.listUserRoleCode(appletUser.getPlatformUserId());
        loginUser.setRoleCodeList(roleCodeList);
        if(ObjectUtil.isNotEmpty(sysUser)){
            SysOrg sysOrg = sysOrgMapper.selectById(sysUser.getOrgId());
            loginUser.setDataScopeList(CollectionUtil.newArrayList());
            loginUser.setPermissionCodeList(CollectionUtil.newArrayList());
            loginUser.setOrgCode(sysOrg.getCode());
            loginUser.setOrgName(sysOrg.getName());
            loginUser.setOrgId(sysUser.getOrgId());
            loginUser.setPlatformUserId(sysUser.getId());
        }
        //重新设置reids缓存
        String userId = loginUser.getUserId();
        String newToken=loginUser.getTokenValue();
        Long longTime = 24 * 60 * 60L;
        //删除历史信息
        RedisStaticUtil.hdel(RedisConstant.LOGIN_REDIS_TOKEN, userId);
        RedisStaticUtil.del(RedisConstant.LOGIN_REDIS_USERINFO+newToken);
        //保存新信息
        RedisStaticUtil.hset(RedisConstant.LOGIN_REDIS_TOKEN, userId, newToken);
        RedisStaticUtil.set(RedisConstant.LOGIN_REDIS_USERINFO+newToken, JSONObject.toJSONString(loginUser), longTime);
        return BaseRespUtil.Success(loginUser);
    }
}
